﻿using System;
using System.Text;
using System.Text.RegularExpressions;
using Org.Flowertwig.Media.Information.Interfaces;

namespace Org.Flowertwig.Media.Information.MediaIdentifiers
{
    public class SerieIdentifier
    {
        //static Regex _regExp = new Regex(@".*\\(?<Name>[a-zA-Z0-9\.\ \'\-]+)[\.|\ ][S|s]{0,1}(?<Season>[0-9]{1,2})[E|e|X|x](?<Episode>[0-9]{0,2}).*[\\|.].*", RegexOptions.Compiled);
        static Regex _regExpDirectory = new Regex(@"\\*(?<Name>[a-zA-Z0-9\.\ \'\-]+)[\.|\ ][S|s]{0,1}(?<Season>[0-9]{1,2})[E|e|X|x](?<Episode>[0-9]{0,2}).*[\\|.].*", RegexOptions.Compiled);

        public static bool TryIdentify(IMedia media, out IIdentifierInfo identifierInfo)
        {
            identifierInfo = null;

            string name;

            Match m = _regExpDirectory.Match(media.Name);
            if (m.Success)
            {
                if (m.Groups.Count == 4)
                {
					var sb = new StringBuilder(m.Groups["Name"].Value.ToLower());
					sb.Replace('.', ' ');
					sb.Replace('\'',' ');
					sb.Replace('-',' ');
					name = sb.ToString();
                    int seasonNr = 0;
                    int.TryParse(m.Groups["Season"].Value, out seasonNr);
                    int episodeNr = 0;
                    int.TryParse(m.Groups["Episode"].Value, out episodeNr);


                    identifierInfo = new SerieIdentifierInfo
                                         {
                                             SearchWord = name,
                                             SeasonNumber = seasonNr,
                                             EpisodeNumber = episodeNr
                                         };
                    return true;
                }
            }
            return false;
        }

        private class SerieIdentifierInfo : IdentifierInfo
        {
            public int SeasonNumber { get; set; }
            public int EpisodeNumber { get; set; }
        }

        public static string GetInformationId(Serie serie, IIdentifierInfo identifierInfo)
        {
            var serieIdentifierInfo = identifierInfo as SerieIdentifierInfo;
            if (serieIdentifierInfo == null)
                return null;

            foreach (var season in serie.Seasons)
            {
                // If this is not the same season, move to next.
                if (season.Number != serieIdentifierInfo.SeasonNumber)
                    continue;

                foreach (var episode in season.Episodes)
                {
                    if (episode.Number == serieIdentifierInfo.EpisodeNumber)
                    {
                        return episode.Id;
                    }
                }
            }

            return null;
        }
    }
}
